package controllers;

import models.TA014;
import models.TA015;
import play.data.binding.ParamNode;
import play.data.validation.Validation;
import play.mvc.Controller;

import java.util.List;

/**
 * Created by xuyang on 2018/3/20.
 */
public class ReformatTemplate extends Controller {

    public static void edit(Long id, Long sid) {
        TA014 splitTemplate = TA014.findById(sid);

        if (id == null ) {
            render(null, sid, splitTemplate);
        }

        TA015 entity = TA015.findById(id);

        render(entity, sid, splitTemplate);
    }

    public static void save(Long id) {
        Long split_template_id = Long.valueOf(params.get("sid"));

        TA014 splitTemplate = TA014.findById(split_template_id);

        TA015 entity;
        if (id != null ) {
            entity = TA015.findById(id);
        } else {
            entity = new TA015();
            entity.split_template = splitTemplate;
        }

        entity.edit(ParamNode.convert(params.all()), "entity");
        Validation.ValidationResult vr = validation.valid(entity);

        if (!validation.hasErrors()) {
            entity.save(); // explicit save here
            flash.success("Successfully updated.");

            edit(id, split_template_id);
        } else{
            flash.error("Validate failed: %s", vr.error.message());
            edit(id, split_template_id);
        }
    }

    public static void remove(Long id) {
        TA015 entity = TA015.findById(id);

        if (entity == null) {
            notFound();
        } else {
            String name = entity.reformat_template_name;
            entity.delete();
            flash.success("Successfully deleted %s", name);
            redirect(request.headers.get("referer").value());
        }
    }
}
